<template>
    <div class="app">
        <Header/>

        <div class="app-main">
            <div class="center">
                <div class="hd_survey_title">
                    <h1>{{surveyDetail.title}}</h1>
                    <div class="hd_survey_time">
                        <span>开始时间：{{surveyDetail.startTime.substring(0,10)}}</span>
                        <span>结束时间：{{surveyDetail.endTime.substring(0,10)}}</span>
                        <span>发布单位：{{surveyDetail.deptName}}</span>
                    </div>
                </div>

                <div>
                    <el-form ref="ref_form">
                        <div v-for="(topic,index) in topicList">
                            <div v-for="(item) in topic">
                                <!--单选-->
                                <div v-if="item.type === 'RADIO_BLANK'">
                                    <el-form-item :label="(index+1) +'、'+item.title">
                                        <span v-if="item.isNecessary===0">
                                            <span>(必选项)</span>
                                            <span class="red">*</span>
                                        </span>

                                        <br/>
                                        <el-radio-group v-model="radioData[index]"
                                                        @change="((label)=>{changeBarStatus(label, item, index)})">
                                            <el-radio :label="option.id" v-for="option in item.optionDtoList">
                                                {{option.content}}
                                            </el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                </div>
                                <!--多选-->
                                <div v-if="item.type === 'CHECK_BLANK'">
                                    <el-form-item :label="(index+1) +'、'+item.title">
                                        <span v-if="item.isNecessary===0">
                                            <span>(必选项)</span>
                                            <span>(可多选，最少选{{item.checkMin}}个，最多选{{item.checkMax}}个)</span>
                                            <span class="red">*</span>
                                        </span>
                                        <br/>
                                        <el-checkbox-group v-model="checkboxList[index]"
                                                           @change="((label)=>{changeBarStatus(label, item, index)})">
                                            <el-checkbox :label="option.id" v-for="option in item.optionDtoList">
                                                {{option.content}}
                                            </el-checkbox>
                                        </el-checkbox-group>
                                    </el-form-item>
                                </div>
                                <!--单选图片-->
                                <div v-if="item.type === 'RADIO_PIC'">
                                    <el-form-item :label="(index+1) +'、'+item.title">
                                        <span v-if="item.isNecessary===0">
                                            <span>(必选项)</span>
                                            <span class="red">*</span>
                                        </span>
                                        <br/>
                                        <el-radio-group v-model="radioData[index]"
                                                        @change="((label)=>{changeBarStatus(label, item, index)})">
                                            <el-radio :label="option.id" v-for="option in item.optionDtoList">
                                                <img :src="option.content"
                                                     width="100px" height="80px"/>
                                            </el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                </div>
                                <!--多选图片-->
                                <div v-if="item.type === 'CHECK_PIC'">
                                    <el-form-item :label="(index+1) +'、'+item.title">
                                        <span v-if="item.isNecessary===0">
                                            <span>(必选项)</span>
                                            <span>(可多选，最少选{{item.checkMin}}个，最多选{{item.checkMax}}个)</span>
                                            <span class="red">*</span>
                                        </span>
                                        <br/>
                                        <el-checkbox-group v-model="checkboxList[index]"
                                                           @change="((label)=>{changeBarStatus(label, item, index)})">
                                            <el-checkbox :label="option.id" v-for="option in item.optionDtoList">
                                                <img :src="option.content"
                                                     width="100px" height="80px"/>
                                            </el-checkbox>
                                        </el-checkbox-group>
                                    </el-form-item>
                                </div>
                                <!--文本-->
                                <div v-if="item.type === 'TEXT'">
                                    <el-form-item :label="(index+1) +'、'+item.title">
                                        <span v-if="item.isNecessary===0">
                                            <span>(必选项)</span>
                                            <span>(最少输入{{item.textSizeMIn}}个字，最多输入{{item.textSizeMax}}个字)</span>
                                            <span class="red">*</span>
                                        </span>
                                        <br/>
                                        <el-input type="textarea" v-model="textData[index]" style="width: 50%"
                                                  @change="((label)=>{changeBarStatus(label, item, index)})"></el-input>
                                    </el-form-item>
                                </div>

                            </div>
                        </div>

                    </el-form>

                    <div class="my_center">
                        <span class="my_line">请输入验证码：</span>
                        <span class="my_line">
                            <el-input type="text" v-model="form.code" class="my_code"></el-input>
                        </span>
                        <span class="my_line"><SIdentify :identifyCode="identifyCode"></SIdentify></span>
                        <span class="my_line">
                            <a href="javascript:void(0);" @click="refreshCode" tabindex="-1">看不清楚？换张图片</a>
                        </span>
                    </div>

                    <div class="my_center">
                        <el-button type="primary" @click="submitForm('ref_form')">提交问卷</el-button>
                    </div>

                </div>
            </div>
        </div>

        <div class="foot-wrap">
            <iframe
                id="data_detail"
                height='218'
                src="http://www.sc.gov.cn/10462/c106307/foot_newer_1200.shtml"
                width="100%" frameborder="0"
                @load="ch"
            ></iframe>
        </div>

    </div>
</template>

<script>
    import Header from "@/components/Header";
    import {getRequest, postRequest} from '@/api'
    import SIdentify from "@/components/utils/SIdentify.vue";
  //  import router from "../router";

    export default {
        name: "SurveySubmit",
        components: {
            Header, SIdentify
        },
        data() {
            return {
                surveyId: "",
                surveyDetail: {
                    title: "",
                    startTime: "",
                    endTime: "",
                    deptName: "",
                },
                topicList: [],
                submitData: [],
                checkboxList: [],
                textData: [],
                radioData: [],
                mustFillTopic: [],

                //验证码
                identifyCode: "",
                identifyCodes: "0123456789abcdwerwshdjeJKDHRJHKOOPLMKQ",
                form: {
                    code: ""
                },

                //防重复提交
                submitted: false

            };
        },
        methods: {

            //获取问卷详情数据
            getDetail() {
                let url = '/sys/sysMember/getQuestionDetailsPage';
                let params = {
                    id: this.surveyId
                };
                getRequest(url, params).then(res => {
                    if (res.data.status == 'success') {
                        this.surveyDetail = res.data.data;
                    }
                })
            },
            //获取题目详情数据
            getTopicDetail() {
                let url = '/sys/sysMember/getSelectItem';
                let params = {
                    id: this.surveyId
                };
                getRequest(url, params).then(res => {
                    if (res.data.status == 'success') {
                        this.topicList = res.data.data;
                        //绑定初始数据
                        for (let i = 0; i < res.data.data.length; i++) {
                            let topic = this.topicList[i][0];
                            if (topic.type === "CHECK_BLANK" || topic.type === "CHECK_PIC") {
                                this.checkboxList[i] = [];
                            } else if (topic.type === "RADIO_BLANK" || topic.type === "RADIO_PIC") {
                                this.radioData[i] = "";
                            } else if (topic.type === "TEXT") {
                                this.textData[i] = "";
                            }
                            //必答题数量
                            if (topic.isNecessary === 0) {
                                this.mustFillTopic.push(topic.itemId);
                            }
                        }
                    }
                })


            },

            //答题改变事件
            changeBarStatus(label, item, index) {

                if (item.type === "RADIO_BLANK") {
                    this.submitData[index] = {
                        "itemId": item.itemId,
                        "type": "RADIO_BLANK",
                        "options": [{
                            "optionId": label
                        }]
                    }
                }
                if (item.type === "RADIO_PIC") {
                    this.submitData[index] = {
                        "itemId": item.itemId,
                        "type": "RADIO_PIC",
                        "options": [{
                            "optionId": label
                        }]
                    }
                }
                if (item.type === "CHECK_BLANK") {
                    let options = [];
                    for (let i = 0; i < this.checkboxList[index].length; i++) {
                        options.push({
                            "optionId": this.checkboxList[index][i]
                        })
                    }
                    this.submitData[index] = {
                        "itemId": item.itemId,
                        "type": "CHECK_BLANK",
                        "options": options
                    }
                }
                if (item.type === "CHECK_PIC") {
                    let options = [];
                    for (let i = 0; i < this.checkboxList[index].length; i++) {
                        options.push({
                            "optionId": this.checkboxList[index][i]
                        })
                    }
                    this.submitData[index] = {
                        "itemId": item.itemId,
                        "type": "CHECK_PIC",
                        "options": options
                    }
                }
                if (item.type === "TEXT") {
                    this.submitData[index] = {
                        "itemId": item.itemId,
                        "type": "TEXT",
                        "options": [{
                            "optionId": item.optionDtoList[0].id,
                            "content": label
                        }]
                    }
                }
            },


            //问卷提交
            submitForm(formName) {
                if(this.submitted){
                    this.$message.error('已提交成功、请勿重复提交');
                    return;
                }

                if (this.checkIsComplete() && this.checkIdentifyCodes()) {
                    let url = '/sys/sysMember/optionsCount';

                    let formData = new FormData();
                    formData.append('id', this.surveyId);
                    formData.append('items', JSON.stringify(this.submitData));

                    postRequest(url, formData).then(res => {
                        if (res.data.status == 'success') {
                            this.submitted = true;
                            this.$message.success('提交成功');
                            //延迟刷新页面
                            setTimeout( function(){
                                location.reload();
                            }, 2 * 1000 );

                        } else {
                            if (res.data.data.errorMsg) {
                                this.$message.error(res.data.data.errorMsg);
                            } else {
                                this.$message.error('提交失败');
                            }
                        }
                    })
                }


            },

            //验证必填题是否答完
            checkIsComplete() {
                let mark = 0;
                for (let i = 0; i < this.submitData.length; i++) {
                    if (this.submitData[i]) {
                        mark++;
                    }
                }
                if (mark < this.mustFillTopic.length) {
                    this.$message.error('必填题不能为空');
                    return false;
                }
                return true;
            },

            //切换验证码[前端方式]
            refreshCode() {//
                this.identifyCode = "";

                this.makeCode(this.identifyCodes, 4);

            },
            randomNum(min, max) {
                max = max + 1
                return Math.floor(Math.random() * (max - min) + min)
            },
            // 随机生成验证码字符串
            makeCode(data, len) {
                for (let i = 0; i < len; i++) {
                    this.identifyCode += data[this.randomNum(0, data.length - 1)]
                }
            },
            //校验验证码
            checkIdentifyCodes() {
                let userIdentifyCode = this.form.code;
                if (!userIdentifyCode) {
                    this.$message.error('验证码不能为空');
                    return false;
                }
                if (userIdentifyCode.toLowerCase() !== this.identifyCode.toLowerCase()) {
                    this.$message.error('验证码输入有误');
                    return false;
                }
                return true;
            },
        },
        //初始化时执行
        created() {
            //从url中获取id
            this.surveyId = this.$route.query.id;

            this.getDetail();

            this.getTopicDetail();

            this.refreshCode();
        }
    }
</script>

<style scoped>
    .my_center {
        text-align: center;
        margin-top: 20px;
    }

    .my_line {
        display: inline-block;
        vertical-align: middle;
    }

    /deep/ .el-radio {
        display: block;
        line-height: 23px;
        white-space: normal;
        margin-right: 0;
        margin-top: 10px;
    }

    .el-checkbox {
        display: block;
        line-height: 23px;
        white-space: normal;
        margin-right: 0;
        margin-top: 10px;
    }

    .app-main {
        overflow: hidden;
    }

    .app-main .center {
        width: 1200px;
        margin: 20px auto;
        background-color: white;
        padding: 0 20px 25px;
    }

    .hd_survey_title {
        border-bottom: 2px solid #ccc;
        padding-bottom: 20px;
    }

    .hd_survey_title h1 {
        font-size: 36px;
        font-weight: 500;
        padding-top: 30px;
        color: #4c4c4c;
        line-height: 50px;
        text-align: center;
        word-wrap: break-word;
        margin: 20px 0;
    }

    .hd_survey_time {
        margin-top: 12px;
        color: #4c4c4c;
        font-size: 16px;
        line-height: 23px;
        text-align: center;
    }

    .hd_survey_time span {
        margin-right: 20px;
    }

    .red {
        color: red;
    }
</style>
